package com.water_work_form.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.water_work_form.entity.RecordProteinNitrogenDetection;
import com.water_work_form.mapper.BasicFormMapper;
import com.water_work_form.mapper.RecordProteinNitrogenDetectionMapper;
import com.water_work_form.service.RecordProteinNitrogenDetectionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 记录——蛋白性氮检测原始记录 服务实现类
 * </p>
 *
 * @author xuke
 * @since 2023-09-14
 */
@Service
public class RecordProteinNitrogenDetectionServiceImpl extends ServiceImpl<RecordProteinNitrogenDetectionMapper, RecordProteinNitrogenDetection> implements RecordProteinNitrogenDetectionService {

    @Autowired
    RecordProteinNitrogenDetectionMapper recordProteinNitrogenDetectionMapper;

    @Autowired
    BasicFormMapper basicFormMapper;

    @Value("${file.templateFilePath}")
    private String templateFilePath;

    @Value("${file.destFilePath}")
    private String destFilePath;


    /**
     * 记录——蛋白性氮检测原始记录 项目查询（三个查询项+分页+排序）
     * @param recordMonth 记录年月对应记录日期（record_date）的年月部分 若为空则不进行此项查询，否则选取record_date的前7位即“yyyy-MM”进行校验，返回符合的数据
     * @param reviewUser 审核人（review_user_name） 若为空则不进行此项查询，否则进行模糊查询
     * @param status 项目状态（status） 若为空则不进行此项查询，否则返回对应数据
     * @param current 分页查询 当前页数
     * @param size 分页查询 每页最大数据量
     * @return 返回所有符合上述条件的数据 按照状态（status）、记录日期（record_date）的前后顺序进行升序排序
     */
    @Override
    public IPage<RecordProteinNitrogenDetection> selectRecordProteinNitrogenDetection(String recordMonth, String reviewUser, String status, Integer current, Integer size){
        QueryWrapper<RecordProteinNitrogenDetection> queryWrapper = new QueryWrapper<>();
        if(!recordMonth.isEmpty()){
            queryWrapper.apply("LEFT(record_date,7) = {0} ",recordMonth);
        }
        if(!reviewUser.isEmpty()){
            queryWrapper.like("review_user_name",reviewUser);
        }
        if(!status.isEmpty()){
            queryWrapper.eq("status",status);
        }
        queryWrapper.orderByAsc("status", "record_date");
        IPage<RecordProteinNitrogenDetection> page = new Page<>(current,size);
        return this.page(page,queryWrapper);
    }

    /**
     * 记录——蛋白性氮检测原始记录 项目查询
     * @param recordMonth 记录年月 若非空匹配查询
     * @param reviewUser 审核人姓名 若非空匹配查询
     * @return 返回相应数据 领用日期（consume_date）的顺序进行升序排序
     */
    @Override
    public List<RecordProteinNitrogenDetection> listRecordProteinNitrogenDetection(String recordMonth, String reviewUser){
        QueryWrapper<RecordProteinNitrogenDetection> queryWrapper = new QueryWrapper<>();
        if(!recordMonth.isEmpty()){
            queryWrapper.apply("LEFT(record_date,7) = {0} ",recordMonth);
        }
        if(!reviewUser.isEmpty()){
            queryWrapper.eq("review_user_name", reviewUser);
        }
        queryWrapper.orderByAsc("record_date");
        return recordProteinNitrogenDetectionMapper.selectList(queryWrapper);
    }

    /**
     * 记录——蛋白性氮检测原始记录 基础表数据查询
     * @param name form表name
     * @return 返回符合的数据 以表名为键
     */
    @Override
    public Map<String,Object> selectBasicProteinNitrogenDetection(String name) {
        Map<String,Object> map = new HashMap<>();
        map.put("form",basicFormMapper.getOneByName(name));
        return map;
    }

    /**
     * 记录——蛋白性氮检测原始记录 数据表导出
     * @param recordProteinNitrogenDetectionList 需要导出的数据表
     * @throws IOException 异常
     */
    @Override
    public void downloadRecordProteinNitrogenDetection(List<RecordProteinNitrogenDetection> recordProteinNitrogenDetectionList, String recordMonth, String reviewUserName) throws IOException {

        Map<String, Object> data = new HashMap<String, Object>();
        List<String> formatRecordDate  = new ArrayList<>();
        List<Map<String,Object>> formatList = new ArrayList<Map<String,Object>>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd");
        formatRecordDate  = recordProteinNitrogenDetectionList.stream()
                .map(recordProteinNitrogenDetection -> dateFormat.format(recordProteinNitrogenDetection.getRecordDate()))
                .collect(Collectors.toList());
        for (int i = 0;i < recordProteinNitrogenDetectionList.size();i++){
            Map<String,Object> map = new HashMap<>();
            map.put("list",recordProteinNitrogenDetectionList.get(i));
            map.put("recordDay",formatRecordDate.get(i));
            formatList.add(map);
        }
        data.put("lists",formatList);
        data.put("recordMonth", recordMonth);
        data.put("reviewUserName", reviewUserName);
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure config = Configure.builder()
                .bind("lists", policy).build();
        XWPFTemplate compile = XWPFTemplate.compile(templateFilePath + "RecordProteinNitrogenDetection.docx",config);
        compile.render(data);
        compile.writeToFile(destFilePath + "out_recordProteinNitrogenDetection.docx");
        compile.close();
    }



}
